<template>
	<jk-dialog
		:dialog-state="showDialog"
		title="任务处理"
		width="900px"
		:confirm-btn-loading="confirmBtnLoading"
		:show-content-loading="showLoading"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="140px" :show-message="false">
			<div class="flex-center">
				<el-tag effect="plain" size="large" class="margin-bottom-10" style="font-weight: 700;font-size: 22px;">
					<span class="el-icon-files item-gap"></span>
					<span>{{ ruleForm.machineName }}</span>
				</el-tag>
			</div>
			<div class="margin-bottom-4 flex-between-center">
				<el-tag type="primary" effect="plain" class="">
					<span class="el-icon-tickets item-gap"></span>
					<span>基本信息</span>
				</el-tag>
				<jk-state-bar :state="recordItem.openingState" :state-list="stateList"></jk-state-bar>
			</div>
			<jk-card>
				<el-row class="flex-start-center-wrap">
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="机器品种">
							<span class="read-only-2">{{ ruleForm.productName }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="计划品种" prop="prdNoticeMachineChangeId">
							<remote-machine-task-input
								placeholder="计划品种"
								only-key="prdNoticeMachineChangeId"
								query-name="planProductName"
								:form-data="ruleForm"
								@on-select="onSelectMachineTaskChange"
							></remote-machine-task-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="机器批号">
							<span class="read-only-2">{{ ruleForm.batchCode || '无' }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="计划批号">
							<span class="read-only-2">{{ ruleForm.planBatchCode || '无' }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-0" label="改纺时间">
							<span class="read-only-2">{{ ruleForm.startDateTime || '无' }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-0" label="生产订单">
							<span class="read-only-2">{{ ruleForm.productOrderCode || '无' }}</span>
						</el-form-item>
					</el-col>
				</el-row>
			</jk-card>
			<div class="flex-between-center margin-bottom-4 margin-top-10">
				<el-tag type="primary" effect="plain" class="">
					<span class="el-icon-odometer item-gap"></span>
					<span>仪表信息</span>
				</el-tag>
				<span v-if="isDiff" type="error" class="el-icon-warning" style="color: #F95457;font-size: 13px;"> 品种不一致，谨慎操作!</span>
			</div>
			<jk-card>
				<el-row class="flex-start-center-wrap">
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="开台时间" prop="startTime">
							<div class="flex-start-center">
								<el-date-picker v-model="ruleForm.startTime" clearable type="datetime" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" placeholder="开台时间" @change="onTimeChange($event, 1)" />
								<stopRecordBar
									:form-data="ruleForm"
									@on-confirm="onConfirmBtnOfStopRecordBar($event, 1)"
								></stopRecordBar>
							</div>
						</el-form-item>
					</el-col>
					<!--已了机的可以修改了机参数-->
					<el-col v-show="recordItem.openingState === 0" :span="12">
						<el-form-item v-if="recordItem.openingState === 0" class="margin-bottom-10" label="了机时间" prop="endTime">
							<div class="flex-start-center">
								<el-date-picker v-model="ruleForm.endTime" clearable type="datetime" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" placeholder="了机时间" @change="onTimeChange($event, 0)" />
								<stopRecordBar
									:form-data="ruleForm"
									@on-confirm="onConfirmBtnOfStopRecordBar($event, 0)"
								></stopRecordBar>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<!--络筒不采集米数，不做必填-->
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="开台表数(M)" prop="startOutput">
							<jk-number-input v-model="ruleForm.startOutput" placeholder="开台表数(M)" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="开台表数(kg)" prop="startOutputKg">
							<jk-number-input v-model="ruleForm.startOutputKg" placeholder="开台表数(kg)" />
						</el-form-item>
					</el-col>

					<!--操作类型为"了机"才允许输入的字段-->
					<el-col v-show="recordItem.openingState === 0" :span="12">
						<el-form-item v-if="recordItem.openingState === 0" class="margin-bottom-10" label="了机表数(M)" prop="endOutput">
							<jk-number-input v-model="ruleForm.endOutput" placeholder="了机表数(M)" />
						</el-form-item>
					</el-col>
					<el-col v-show="recordItem.openingState === 0" :span="12">
						<el-form-item v-if="recordItem.openingState === 0" class="margin-bottom-10" label="了机表数(kg)" prop="endOutputKg">
							<jk-number-input v-model="ruleForm.endOutputKg" placeholder="了机表数(kg)" />
						</el-form-item>
					</el-col>
				</el-row>
			</jk-card>
		</el-form>
	</jk-dialog>
</template>

<script>
    import { tipsBar } from '../../../utils/jk/jk-tool';
    import { mathJsSub } from '../../../utils/jk/jk-cals';
    import {
        productionMachineShiftProductOutputUpdate,
        productionPrdNoticeMachineChangeGetMachineData
    } from '../../../api/production/xsOpen';
    import stopRecordBar from '../productOpenCloseMachine/components/stopRecordBar';
    import remoteMachineTaskInput from './components/remote-machine-task-input';
    import stateOptions from './state-options';
    import splitProductName from './splitProductName';
    export default {
        components: {
            remoteMachineTaskInput,
            stopRecordBar
        },
        mixins: [stateOptions, splitProductName],
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            recordItem: {
                type: Object,
                default() {
                    return {};
                }

            }
        },
        data() {
            return {
                showLoading: false,
                showDialog: false,
                confirmBtnLoading: false,
                ruleForm: {
                    'id': '',
                    'processCode': '',
                    'prdNoticeMachineChangeId': null,
                    // 开台参数
                    'startOutput': null,
                    'startTime': '',
                    'startOutputKg': null,
                    // 了机参数
                    'endOutput': null,
                    'endTime': '',
                    'endOutputKg': null
                },
                rules: {
                    prdNoticeMachineChangeId: [{ required: true, trigger: 'change' }],
                    startTime: [{ required: true, trigger: 'change' }],
                    startOutput: [{ required: true, trigger: 'change' }],
                    startOutputKg: [{ required: true, trigger: 'change' }],
                    endOutput: [{ required: true, trigger: 'change' }],
                    endOutputKg: [{ required: true, trigger: 'change' }],
                    endTime: [{ required: true, trigger: 'change' }]
                },
                isDiff: false
            };
        },
        methods: {
            // 判断设备品种和计划品种是否一致
            isDiffTheProduct() {
                if (this.ruleForm.productName && this.ruleForm.planProductName) {
                    // 先去掉所有空格和中文并转成大写，再进行对比
                    this.isDiff = this.getSplitProductName(this.ruleForm.productName) !== this.getSplitProductName(this.ruleForm.planProductName);
                } else {
                    this.isDiff = false;
                }
            },
            onSelectMachineTaskChange(e) {
                if (e && Object.keys(e).length) {
                    this.$set(this.ruleForm, 'prdNoticeMachineChangeId', e.id);
                    this.$set(this.ruleForm, 'planProductId', e.productId);
                    this.$set(this.ruleForm, 'planProductCode', e.productCode);
                    this.$set(this.ruleForm, 'planProductName', e.productName);
                    this.$set(this.ruleForm, 'planBatchId', e.batchId);
                    this.$set(this.ruleForm, 'planBatchCode', e.batchCode);
                    this.$set(this.ruleForm, 'productOrderCode', e.productOrderCode);

                    this.isDiffTheProduct();
                }
            },
            onTimeChange(e, type) {
                this.getGatherMachineDataRequest(type);
            },
            onConfirmBtnOfStopRecordBar(item, type) {
                if (Object.keys(item).length) {
                    if (type === 1) {
                        this.$set(this.ruleForm, 'startTime', JSON.parse(JSON.stringify(item)).systemStartDateTime);
                    } else if (type === 0) {
                        this.$set(this.ruleForm, 'endTime', JSON.parse(JSON.stringify(item)).systemEndDateTime);
                    }
                    this.onTimeChange(this.ruleForm.startTime, type);
                } else {
                    tipsBar(this, 'custom', 'warning', '请选择!');
                }
            },
            onJump() {
                this.$toMainRouter({
                    name: 'XsClose',
                    query: {
                        machineCode: this.ruleForm.machineCode
                    }
                });
            },
            onSpinNumChange() {
                if (this.ruleForm.endSpinNumber) {
                    this.ruleForm.startSpinNumber = this.ruleForm.startSpinNumber || 0;
                    this.$set(this.ruleForm, 'openSpinCount', mathJsSub(this.ruleForm.endSpinNumber, this.ruleForm.startSpinNumber));
                }
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.saveRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            saveRequest() {
                const params = {
                    'id': this.recordItem.id,
                    'prdNoticeMachineChangeId': this.ruleForm.prdNoticeMachineChangeId,

                    'startOutput': this.ruleForm.startOutput,
                    'startTime': this.ruleForm.startTime,
                    'startOutputKg': this.ruleForm.startOutputKg,

                    'endOutput': this.ruleForm.endOutput,
                    'endTime': this.ruleForm.endTime,
                    'endOutputKg': this.ruleForm.endOutputKg
                };
                this.confirmBtnLoading = true;
                productionMachineShiftProductOutputUpdate(params).then(res => {
                    this.confirmBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$emit('on-confirm');
                    }
                });
            },
            onVisibleChange(e) {
                if (!e) {
                    this.isDiff = false;
                }
                this.$emit('on-visible-change', e);
            },
            // 获取指定机台采集的仪表数据
            getGatherMachineDataRequest(type) {
                if (this.ruleForm.machineId && this.ruleForm.machineCode) {
                    return productionPrdNoticeMachineChangeGetMachineData({
                        machineId: this.ruleForm.machineId,
                        machineCode: this.ruleForm.machineCode,
                        selectDateTime: type === 1 ? this.ruleForm.startTime : this.ruleForm.endTime
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res || {};
                            // 开台
                            if (type === 1) {
                                this.$set(this.ruleForm, 'startOutput', resData.currentOutput);
                                this.$set(this.ruleForm, 'startOutputKg', resData.currentOutputKg);
                            } else if (type === 0) {
                                // 了机
                                this.$set(this.ruleForm, 'endOutput', resData.currentOutput);
                                this.$set(this.ruleForm, 'endOutputKg', resData.currentOutputKg);
                            }
                        }
                    });
                }
            },
            // 设置表单项的必填状态
            setFormItemRequiredState() {
                // 络筒不采集米数，不做必填
                if (this.ruleForm.processCode === 'LT') {
                    // 产量M
                    this.$set(this.rules.startOutput[0], 'required', false);
                    this.$set(this.rules.endOutput[0], 'required', false);
                    // 产量kg
                    this.$set(this.rules.startOutputKg[0], 'required', true);
                    this.$set(this.rules.endOutputKg[0], 'required', true);
                } else {
                    // 产量M
                    this.$set(this.rules.startOutput[0], 'required', true);
                    this.$set(this.rules.endOutput[0], 'required', true);
                    // 产量kg
                    this.$set(this.rules.startOutputKg[0], 'required', true);
                    this.$set(this.rules.endOutputKg[0], 'required', true);
                }
            },
            async getDependentData() {
                this.showLoading = true;
                this.setFormItemRequiredState();
                if (this.ruleForm.startTime) await this.getGatherMachineDataRequest(1);
                if (this.ruleForm.endTime) await this.getGatherMachineDataRequest(0);
                this.$nextTick(() => {
                    this.$refs.ruleForm.clearValidate();
                });
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                const cpData = {
                    'id': this.recordItem.id,
                    'machineId': this.recordItem.machineId,
                    'machineCode': this.recordItem.machineCode,
                    'machineName': this.recordItem.machineName,
                    'productName': this.recordItem.productName,
                    'planProductName': this.recordItem.planProductName,
                    'planBatchCode': this.recordItem.planBatchCode,
                    'processCode': this.recordItem.processCode,
                    'processName': this.recordItem.processName,
                    'prdNoticeMachineChangeId': this.recordItem.prdNoticeMachineChangeId || null,
                    'openingState': this.recordItem.openingState,
                    'startOutput': null,
                    'startTime': this.recordItem.startDateTime,
                    'startOutputKg': null,

                    'endOutput': null,
                    'endTime': this.recordItem.endDateTime,
                    'endOutputKg': null
                };
                this.ruleForm = cpData;
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
